<?php

namespace App\Http\Middleware;

use App\Utils\Result;
use App\Utils\Token;
use Closure;
use Illuminate\Http\Request;

class VerifyApiToken
{
    /**
     * The URIs that should be excluded from CSRF verification.
     *
     * @var array
     */
    protected $except = [
        'shop_login',
        'agent_login',
        'saas_login',
        'saas_auto_restart',
        'mp_mp_login',
        'mp_register',
        'mp_login',
        'mp_index_business',
        'mp_index_tenant',
        'mp_device_detail',
        'mp_send_sms_code',
        'mp_article',
        'mp_qa',
        'mp_qa_detail',
        'mp_device_search',
        'fdd_callback',
        'mp_changePassword',
        'payment_notify',
        'create_device',
        'mp_business_conf',
        'mp_update_openid',
        'mp_device_list',
        'mp_qa',
        'mp_qa_detail',
        'mp_mp_reg',
        'agent_agent_login',
        'agent_agent_register',
        'clear_month',
        'business_business_login',
        'mp_upload'
    ];

    /**
     * Handle an incoming request.
     *
     * @param Request $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $routeName = $request->route()->action['as'] ?? '';
        $token = $request->header('Token');
        if(!$token){
            $token = $request->header('token');
        }
        if (in_array($routeName, $this->except) && !$token) {
            return $next($request);
        }

        $platform = $request->route()->action['prefix'];
        if (!$token) {
            return Result::error(403, '缺少Token');
        }
        if (!Token::verifyToken($token, $platform)) {
            return Result::error(403, 'Token无效');
        }

        return $next($request);
    }
}
